package com.jnsw.testkotlin.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;

/**
 * Created by Administrator on 2017/12/14 0014.
 */

public class MyImage extends android.support.v7.widget.AppCompatImageView {
    public MyImage(Context context) {
        super(context);
    }

    public MyImage(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyImage(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
//        super.onDraw(canvas);
        int w = getWidth();
        int h  = getHeight();
        int min = Math.min(w,h);
        Bitmap rawBitmap =  getBitmap(getDrawable());

        int r = min/ 2;//也可以是getMeasuredHeight()/2,本例中我们已经将宽高设置相等了

        Paint paint = new Paint();
        paint.setColor(Color.GREEN);

        //开始绘制 //在view内绘制 中心点坐标即为半径值
//        if (rawBitmap != null){
            BitmapShader  mShader = new BitmapShader(rawBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        Paint mPaintBitmap = new Paint(Paint.ANTI_ALIAS_FLAG);
        //图片
        //设置图片缩放
        if (mShader != null) {
            Matrix mMatrix = new Matrix();
//            log.i("maxtrix-=--",w+"-=-"+rawBitmap.getWidth()+"---"+h+"--=-"+rawBitmap.getHeight());

            mMatrix.setScale((float)w/(rawBitmap.getWidth()),(float)h/rawBitmap.getHeight());
            mShader.setLocalMatrix(mMatrix);
        }
        mPaintBitmap.setShader(mShader);
        Paint mPaintBorder = new Paint(Paint.ANTI_ALIAS_FLAG);

            mPaintBorder.setStyle(Paint.Style.STROKE);//描边
            mPaintBorder.setStrokeWidth(20);//描边宽度
            mPaintBorder.setColor(Color.TRANSPARENT);
            canvas.drawCircle(r, r, r-5 , mPaintBorder); //绘制边框

            canvas.drawCircle(r, r, r,mPaintBitmap);
//        }else {
//            canvas.drawCircle(r, r, r,paint);
//
//        }


    }

    private Bitmap getBitmap(Drawable drawable){
         if (drawable instanceof BitmapDrawable){
            return ((BitmapDrawable)drawable).getBitmap();
        } else {
            return null;
        }
    }

}
